from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import *
from apps.stat.models.stat import Stat
from apps.stat.views.forms.stat_form import StatForm
from apps.core.models.element import Element
from apps.core.models.section import Section


@permission_required("is_staff")
def showStats(request):
    sList = Stat.objects.all()
    return render_to_response("stat_list.html", locals())

@permission_required("is_staff")
def addStats(request):
    initial = {'owner':request.user.id}
    if request.POST:
        form = StatForm(request.POST, initial=initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/plugin/stat")
    else:
        form = StatForm(initial=initial)
    buttonText = "Aggiungi"
    return render_to_response("stat_add.html", locals())

@permission_required("is_staff")
def editStats(request, identifier):
    st = Element.objects.get(id=identifier)
    if st:
        st = Stat.objects.get(related_element=st.id)
    else:
        return HttpResponseRedirect("/plugin/stat")
    initial = st.__dict__
    initial.update(st.related_element.__dict__)
    initial['section'] = initial['section_id']
    initial['owner'] = initial['owner_id']

    
    if request.POST:
        form = StatForm(request.POST, initial = initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/plugin/stat")
    else:
        form = StatForm(initial = initial)
    buttonText = "Modifica"
    return render_to_response("stat_add.html", locals())
